import React, { useCallback, useEffect, useImperativeHandle, useState } from 'react';
import { Button, message, Table, Space, Form, Input } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { SeatInfo } from 'admin/schema/Seat';
import { getSeatList, moveInSeatGroup, moveOutSeatGroup } from 'admin/servers/servers';
import { clearNull } from 'utils/tools';
import '../style.scss';
import { useHistory } from 'react-router-dom';

interface Iprops {
  /**组件的引用 */
  cRef: any;
  /**坐席组Id */
  seatGroupId: number;
  /**坐席列表位置：left：左边；right:右边 */
  layout: 'left' | 'right';
  callback: () => void;
}

const AdjustModel: React.FC<Iprops> = (props: Iprops) => {
  const history = useHistory();
  const [form] = Form.useForm();
  const { seatGroupId, layout, cRef, callback } = props;
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // 搜索内容
  const [searchForm, setSearchForm] = useState<any>({});
  // 批量删除选择项
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  // table列表数据
  const [tableList, setTableList] = useState<SeatInfo[]>([]);
  // 表格刷新
  const [key, setKey] = useState<number>(1);
  // 场景：左右表格操作完，需要刷新列表数据
  // 将handleSearch方法暴露出去。父组件可以通过ref获取到，调用freshTable
  useImperativeHandle(cRef, () => ({
    // 父组件事件传递
    freshTable: () => freshTable(),
  }));
  /**
   * 更新表格key值，触发更新
   */
  const freshTable = () => {
    let num = key;
    num++;
    setKey(num);
  };
  /**
   * 查询table数据
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      if (!seatGroupId) {
        return;
      }
      const params = {
        ...searchForm,
        pageNo: current,
        pageSize: pageSize,
        seatGroupId: seatGroupId,
        ruleGroup: layout === 'left' ? 1 : 0,
      };
      const res = await getSeatList(clearNull(params));
      const { data, count } = res;
      setTableList(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [seatGroupId, current, pageSize, searchForm, layout]);

  useEffect(() => {
    initData();
  }, [initData, key]);

  /**
   * 重置列表
   */
  const handleSearch = (values: any) => {
    setSearchForm({ ...values });
    setCurrent(1);
  };
  /**
   * 新增-移入
   */
  const handleAdd = (id: number) => {
    const data = {
      seatGroupId,
      seatIds: [id],
    };
    moveInSeatGroup(data)
      .then(res => {
        message.success('移入成功');
        setCurrent(1);
        initData();
        callback();
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };

  /**
   * 删除-移出
   */
  const handleDelete = (id: number) => {
    const data = {
      seatGroupId,
      seatIds: [id],
    };
    moveOutSeatGroup(data)
      .then(res => {
        message.success('移出成功');
        setCurrent(1);
        initData();
        callback();
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };
  /**
   * 批量删除-移出
   */
  const batchDelete = (): void => {
    if (selectedIds.length === 0) {
      message.warn('请先选择项');
      return;
    }
    const data = {
      seatGroupId,
      seatIds: selectedIds,
    };
    moveOutSeatGroup(data)
      .then(res => {
        message.success('批量移出成功');
        setCurrent(1);
        initData();
        callback();
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };
  /**
   * Table列描述数据对象
   */
  const columns: ColumnsType<SeatInfo> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 100,
    },
    {
      title: '坐席工号',
      dataIndex: 'seatsNumber',
    },
    {
      title: '坐席姓名',
      dataIndex: 'nickName',
    },
    {
      title: '当前坐席组',
      dataIndex: 'seatGroupName',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 120,
      render: (text, record, index) => (
        <Space size="small">
          {layout === 'left' && (
            <Button type="link" onClick={() => handleAdd(record.userId)}>
              移入
            </Button>
          )}
          {layout === 'right' && (
            <Button type="link" onClick={() => handleDelete(record.userId)}>
              移出
            </Button>
          )}
        </Space>
      ),
    },
  ];
  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      console.log('复选-选择的row', selectedRowKeys);
      setSelectedIds(selectedRowKeys);
    },
  };
  if (layout === 'right') {
    // 右侧去掉【当前坐席组】列
    columns.splice(3, 1);
  }

  /**
   * 重置搜索列表
   */
  const handleReset = () => {
    form.resetFields();
    setSearchForm({});
  };

  return (
    <div className="adjust-seat-model">
      {layout === 'left' && (
        <div className="header">
          <div>
            <span className="title">坐席列表</span>
            <span className="tip">*列表展示企业下不在当前坐席组的坐席</span>
          </div>
          <Form layout="inline" form={form} onFinish={handleSearch}>
            <Form.Item
              label="坐席工号"
              name="seatsNumber"
              getValueFromEvent={event => {
                return event.target.value.replace(/[^0-9]+/g, '');
              }}
            >
              <Input allowClear placeholder="请输入" style={{ width: 130 }} />
            </Form.Item>
            <Form.Item
              label="坐席姓名"
              name="nickName"
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input allowClear placeholder="请输入" style={{ width: 130 }} />
            </Form.Item>
            <Space size="middle">
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
              <Button type="primary" ghost onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form>
        </div>
      )}
      {layout === 'right' && (
        <div className="header">
          <div>
            <span className="title">坐席组成员</span>
            <span className="tip">
              共有<i>{total}</i>位坐席
            </span>
            {tableList.length > 0 && (
              <Button
                type="primary"
                onClick={() => {
                  batchDelete();
                }}
              >
                批量移出
              </Button>
            )}
            <Button
              style={{ float: 'right' }}
              type="primary"
              onClick={() => {
                history.goBack();
              }}
            >
              返回
            </Button>
          </div>
        </div>
      )}
      <div className="mgr-table">
        <Table
          key={'table_' + layout}
          rowSelection={layout === 'right' ? { type: 'checkbox', ...rowSelection } : undefined}
          loading={tableLoading}
          columns={columns}
          dataSource={tableList}
          rowKey="userId"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>
    </div>
  );
};

export default AdjustModel;
